/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.atomojo.tools;

import java.io.Console;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import org.restlet.Client;
import org.restlet.Context;
import org.restlet.data.Protocol;
import org.restlet.data.Reference;
import org.restlet.engine.ClientHelper;

/**
 *
 * @author alex
 */
public class ClientTool {
   static Logger LOG = Logger.getLogger(ClientTool.class.getName()); 
   public static void usage() {
      System.err.println("Usage: "+ClientTool.class.getName()+" ( -token server=token ) ( -auth server=username{:password} | - ) ( -exact ) source-ref target-ref");
   }
   public static String [] getServerArgument(String value)
   {
      int eq = value.indexOf('=');
      if (eq<0) {
         return null;
      }
      String [] values = new String[2];
      values[0] = value.substring(0,eq);
      values[1] = value.substring(eq+1);
      return values;
   }
   public static void main(String[] args) {
      Context context = new Context();
      context.setLogger(LOG);
      
      List<Protocol> clientProtocols = new ArrayList<Protocol>();
      clientProtocols.add(Protocol.HTTP);
      clientProtocols.add(Protocol.HTTPS);
      Client client = new Client(context,clientProtocols);
      
      context.setClientDispatcher(client);
      
      Console console = System.console();
      UserAgent browser = new UserAgent(context);
      FeedSynchronizer feedSync = new FeedSynchronizer(browser);
      int argidx = 0;
      while (argidx<args.length && args[argidx].charAt(0)=='-') {
         if (args[argidx].equals("-token")) {
            argidx++;
            String [] spec = getServerArgument(args[argidx]);
            browser.setAccessToken(spec[0], spec[1]);
         } else if (args[argidx].equals("-auth")) {
            argidx++;
            String [] spec = getServerArgument(args[argidx]);
            if (spec[1].equals("-")) {
               String username = console.readLine("Username:");
               char [] password = console.readPassword("Password:");
               browser.setIdentity(spec[0], username, new String(password));
            } else {
               String [] auth = args[argidx].split(":");
               browser.setIdentity(spec[0], auth[0], auth[1]);
            }
         } else if (args[argidx].equals("-exact")) {
            feedSync.setMode(FeedSynchronizer.Mode.Both);
         }
         argidx++;
      }
      
      if ((args.length-argidx)<2) {
         usage();
         System.exit(1);
      }
      
      Reference sourceFeedRef = new Reference(args[argidx]);
      Reference targetFeedRef = new Reference(args[argidx+1]);
      
      feedSync.sync(sourceFeedRef, targetFeedRef);

   }
}
